import 'dart:async';
import 'dart:math';
import 'package:caici/global.dart';
import 'package:caici/manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

class PanelPage extends StatefulWidget {
  PanelPage({
    Key key,
    this.words,
    this.seconds,
  }) : super(key: key);
  final List<String> words;
  final int seconds;

  @override
  _PanelPageState createState() => _PanelPageState();
}

class _PanelPageState extends State<PanelPage> {
  List _words = [];
  var timer;
  int timing;

  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    setState(() {
      _words = widget.words.map((word) {
        return {'word': word, 'right': false};
      }).toList();
      timing = widget.seconds;
    });

    timer = Timer.periodic(Duration(seconds: 1), (t) {
      setState(() {
        timing = timing >= 1 ? timing - 1 : 0;
      });
      if (timing <= 1) t?.cancel();
    });
    super.initState();
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  String formatTimingString() {
    return '${timing ~/ 60 < 10 ? "0" + (timing ~/ 60).toString() : timing ~/ 60}:${timing % 60 < 10 ? "0" + (timing % 60).toString() : timing % 60}';
  }

  List<Widget> renderWords(words) {
    List<Widget> list = [];
    for (var i = 0; i < words.length; i++) {
      var item = words[i];
      list.add(
        GestureDetector(
          onDoubleTap: () {
            setState(() {
              item['right'] = !item['right'];
            });
          },
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            color: item['right'] ? Global.rightColor : Global.backgroundColor,
            child: Transform.rotate(
              angle: pi / 2,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    item['word'],
                    style: TextStyle(
                      fontSize: MediaQuery.of(context).size.width / 5,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }
    return list;
  }

  int getRightWordsNumber() {
    return _words.where((item) => item['right']).toList().length;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: timing <= 1
          ? Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              padding: EdgeInsets.only(top: Global.padding.top),
              decoration: BoxDecoration(color: Color(0xFFC2B592)),
              child: Stack(
                alignment: AlignmentDirectional.center,
                children: [
                  Container(
                    width: 325,
                    height: 475,
                    padding: EdgeInsets.only(top: Global.padding.top),
                    decoration: BoxDecoration(
                      color: Color(0xFFC2B592),
                      image: DecorationImage(
                        image: AssetImage('assets/images/panel.png'),
                        repeat: ImageRepeat.noRepeat,
                        fit: BoxFit.fitWidth,
                      ),
                    ),
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(height: 140),
                      Text(
                        '得分：${getRightWordsNumber()}分',
                        style: TextStyle(
                          fontSize: 25,
                          fontWeight: FontWeight.w500,
                          color: Global.fontColor,
                        ),
                      ),
                      SizedBox(height: 40),
                      Text(
                        '共猜对：${getRightWordsNumber()}个',
                        style: TextStyle(
                          fontSize: 25,
                          fontWeight: FontWeight.w500,
                          color: Global.fontColor,
                        ),
                      ),
                      SizedBox(height: 40),
                      Text(
                        '用时：${widget.seconds} 秒',
                        style: TextStyle(
                          fontSize: 25,
                          fontWeight: FontWeight.w500,
                          color: Global.fontColor,
                        ),
                      ),
                      SizedBox(height: 55),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SizedBox(width: 150),
                          InkWell(
                            onTap: () {
                              Navigator.of(context).pop();
                            },
                            child: Container(width: 100, height: 35),
                          ),
                        ],
                      ),
                      SizedBox(height: 75),
                    ],
                  ),
                ],
              ))
          : Stack(
              children: [
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  decoration: BoxDecoration(
                    color: Global.backgroundColor,
                  ),
                  child: PageView(
                    scrollDirection: Axis.vertical,
                    reverse: false,
                    controller: PageController(
                      initialPage: 0,
                      viewportFraction: 1,
                      keepPage: true,
                    ),
                    physics: BouncingScrollPhysics(),
                    pageSnapping: true,
                    onPageChanged: (index) {},
                    children: renderWords(_words),
                  ),
                ),
                Positioned(
                  bottom: MediaQuery.of(context).size.height / 2 - 30,
                  right: -40,
                  child: Transform.rotate(
                    angle: pi / 2,
                    child: Text(
                      '剩余时间：' + formatTimingString(),
                      style: TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.w700,
                        color: Global.fontColor,
                      ),
                    ),
                  ),
                ),
                Positioned(
                  bottom: 40,
                  right: 20,
                  child: InkWell(
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                    child: Container(
                      width: 50,
                      height: 50,
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.white.withOpacity(.7),
                          width: 5,
                        ),
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child: Center(
                        child: Icon(
                          Icons.close,
                          size: 40,
                          color: Colors.white.withOpacity(.7),
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
    );
  }
}
